package org.jzentest;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jzentest.dependency.ClassAnalyzer;
import org.jzentest.filetracker.Lister;

public class AutoTest {
	
	private Lister fileLister = new Lister();
	private TestTracker testTracker;
	
	
	private Map<String, Long> fileList = new HashMap<String, Long>();
	private List<File> changed = new ArrayList<File>();
	
	public AutoTest(TestRunner testRunner, ClassAnalyzer analyzer) {
		this.testTracker = new TestTracker(analyzer, testRunner);
	}

	public void watch(String path) throws IOException {
		List<File> fileListingNoSort = fileLister.getFileListingNoSort(new File(path));
		addAll(fileListingNoSort);
		
		testTracker.init(fileListingNoSort);
		
		while(true) {
			List<File> files = fileListingNoSort;
			for(File f : files) {
				if (checkModification(f)) {
					changed.add(f);
				}
			}
			
			testTracker.runTestsForFiles(changed);
			changed.clear();
			try {
				Thread.sleep(2500);
			} catch (InterruptedException e) {
			}
		}
	}

	private boolean checkModification(File f) {
		
		Long time = fileList.get(f.getAbsolutePath());
		if (time == null) {
			fileList.put(f.getAbsolutePath(), f.lastModified());
			return true;
			// file added
		} else {
			if (time != f.lastModified()) {
				// TODO review
				// file modified
				fileList.put(f.getAbsolutePath(), f.lastModified());
				return true;
			}
			// file not changed
		}
		return false;
	}

	private void addAll(List<File> fileListingNoSort) {
		fileList.clear();
		for(File f: fileListingNoSort) {
			fileList.put(f.getAbsolutePath(), f.lastModified());
		}
	}

}
